package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.RandomCharData;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.ssh.CMDUtilShell;
import com.ruoyi.common.utils.ssh.ExecResult;
import com.ruoyi.common.utils.ssh.ExpectShellUtil;
import com.ruoyi.system.domain.GridAccount;
import com.ruoyi.system.domain.GridCmdTemplates;
import com.ruoyi.system.domain.GridLogs;
import com.ruoyi.system.domain.GridPolicy;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 帐号管理Controller
 *
 * @author ruoyi
 * @date 2021-12-21
 */
@RestController
@RequestMapping("/system/account")
public class GridAccountController extends BaseController {
    @Autowired
    private IGridAccountService gridAccountService;

    @Autowired
    private IGridPolicyService gridPolicyService;

    @Autowired
    private IGridCmdTemplatesService gridCmdTemplatesService;

    @Autowired
    private IGridHostService gridHostService;

    @Autowired
    private IGridLogsService gridLogsService;


    /**
     * 获取帐号管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:account:list')")
    @GetMapping(value = "/logs/{hostip}")
    public TableDataInfo getLogsInfo(@PathVariable("hostip") String hostIp) {
        GridLogs logs = new GridLogs();
        logs.setHostIp(hostIp);
        List<GridLogs> list = gridLogsService.selectGridLogsList(logs);
        return getDataTable(list);
    }

    /**
     * 查询帐号管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:account:list')")
    @GetMapping("/list")
    public TableDataInfo list(GridAccount gridAccount) {
        startPage();
        List<GridAccount> list = gridAccountService.selectGridAccountList(gridAccount);
        List<GridAccount> resule = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            GridAccount item = list.get(i);
            GridPolicy gridPolicy = gridPolicyService.selectGridPolicyByPolicyId(item.getPolicyId().intValue());
            item.setPolicyName(gridPolicy.getPolicyName());
            GridCmdTemplates templates = gridCmdTemplatesService.selectGridCmdTemplatesByTemplatesId(item.getTemplatesId().intValue());
            item.setTemplatesName(templates.getTemplatesName());
            resule.add(item);
        }
        return getDataTable(resule);
    }

    /**
     * 查询帐号管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:account:list')")
    @GetMapping("/listbyhost")
    public TableDataInfo listbyhost(String hostId) {
        startPage();
        GridAccount gridAccount = new GridAccount();
        //gridAccount.setHostId(hostId);

        List<GridAccount> list = gridAccountService.selectGridAccountList(gridAccount);

        return getDataTable(list);
    }

    /**
     * 导出帐号管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:account:export')")
    @Log(title = "帐号管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GridAccount gridAccount) {
        List<GridAccount> list = gridAccountService.selectGridAccountList(gridAccount);
        ExcelUtil<GridAccount> util = new ExcelUtil<GridAccount>(GridAccount.class);
        util.exportExcel(response, list, "帐号管理数据");
    }

    /**
     * 获取帐号管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:account:query')")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        return AjaxResult.success(gridAccountService.selectGridAccountByUserId(userId));
    }


    /**
     * 新增帐号管理
     */
    @PreAuthorize("@ss.hasPermi('system:account:add')")
    @Log(title = "帐号管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GridAccount gridAccount) {
        //根据策略修改密码
        return toAjax(gridAccountService.insertGridAccount(gridAccount));
    }


    /**
     * 新增帐号管理
     */
    @PreAuthorize("@ss.hasPermi('system:account:add')")
    @Log(title = "帐号管理", businessType = BusinessType.INSERT)
    @PostMapping("/file")
    public AjaxResult addFile(@RequestBody Object object) {
        //根据策略修改密码
        ArrayList<HashMap> list = new ArrayList<HashMap>();
        HashMap row = list.get(0);
        String fileName = row.get("serverfile").toString();

        File f = new File("D:\\ruoyi\\uploadPath\\" + fileName);
        ExcelUtil util = new ExcelUtil(GridAccount.class);

        InputStream file = null;
        try {
            file = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // List accountList = util.importExcel(f);


        System.out.println("-----------------------");
        return toAjax(1);
    }

    /**
     * 修改帐号管理
     */
    @PreAuthorize("@ss.hasPermi('system:account:edit')")
    @Log(title = "帐号管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GridAccount gridAccount) {
        return toAjax(gridAccountService.updateGridAccount(gridAccount));
    }

    /**
     * 删除帐号管理
     */
    @PreAuthorize("@ss.hasPermi('system:account:remove')")
    @Log(title = "帐号管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(gridAccountService.deleteGridAccountByUserIds(userIds));
    }


   /* @Log(title = "帐号Login", businessType = BusinessType.OTHER)
    @GetMapping("/ssh")
    public String sshHost() {
        JSchUtil js = new JSchUtil("grid", "grid123", "81.68.118.155", 22);
        StringBuffer buffer = new StringBuffer();
        try {
            js.Connection();
            String newpasswd = "Exhau1sted";
            //buffer = js.executeCmd(command);
            try {
                buffer = js.executePasswd(1, newpasswd);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        } catch (JSchException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();

    }*/


    /**
     * 查询帐号管理列表
     */
    @GetMapping("/newpass")
    public AjaxResult newpass(String userId) {
        return AjaxResult.success(gridAccountService.selectGridAccountByUserId(Long.parseLong(userId)));
    }

    /**
     * 查询帐号管理列表
     */
    @PostMapping("/modifyallpass")
    public AjaxResult modifyallpass(@RequestBody Object object) {
        // System.out.println(userIds.length);
        ArrayList<Integer> ids = new ArrayList<Integer>();
        if (object instanceof Integer) {
            ids.add((Integer) object);
        } else {
            ids = (ArrayList<Integer>) object;
        }
        for (int i = 0; i < ids.size(); i++) {
            GridAccount item = gridAccountService.selectGridAccountByUserId(Long.parseLong(ids.get(i).toString()));
            int port = item.getHostPort();
            logger.info(item.toString());
            logger.info("port:" + port);
            HashMap map = execSsh(item, port);
            //修改
            logger.info(">>>map>>>>>>>"+map.toString());
            if (map.get("code").toString().equals("1")) {
                item.setUserPass(map.get("pass").toString());
                item.setNewUserPass("");
                item.setRemark(map.get("code").toString());
                item.setExeStatus("1");//成功
                item.setUpdateBy(SecurityUtils.getUsername());
            } else {
                item.setRemark(map.toString());
                item.setExeStatus("2");//失败
                item.setUpdateBy(SecurityUtils.getUsername());
            }
            gridAccountService.updateGridAccount(item);
        }
        HashMap map = new HashMap();
        map.put("data", "ok");
        return AjaxResult.success(map);
    }

    /*
    1 正常
    100 未知错误
    101 ssh认证失败
    102 命令错误
    103 命令错误*/

    private HashMap execSsh(GridAccount item, int port) {
        GridCmdTemplates gridCmdTemplates = gridCmdTemplatesService.selectGridCmdTemplatesByTemplatesId(item.getTemplatesId().intValue());
        String oldpass = item.getUserPass();
        StringBuffer buffer = new StringBuffer();
        HashMap map = new HashMap();
        String newpasswd = "";
        // try {
        newpasswd = item.getNewUserPass();
        logger.info("========newpasswd===========:" + newpasswd);
        ExecResult result = new ExecResult();
        GridPolicy policy = gridPolicyService.selectGridPolicyByPolicyId(item.getPolicyId().intValue());
        logger.info("========ExeMethon===========" + policy.getExeMethon());
        if (null == newpasswd || newpasswd.trim().length() < 1) {
            int minlen = Integer.parseInt(policy.getPassMin());
            int rule = Integer.parseInt(policy.getPassRule());
            if (rule == 1) {
                //import
            }else if (rule == 2) {
                newpasswd = RandomCharData.createRandomNumPass(minlen);
            } else if (rule == 3) {
                newpasswd = RandomCharData.createRandomCharPass(minlen);
            } else if (rule == 4) {
                newpasswd = RandomCharData.createRandomCharSymbolPass(minlen);
            }
            //try {
        }
        logger.info("========final newpasswd===========:" + newpasswd);

        if (policy.getExeMethon().equals("1")) {//手动
            logger.info("========ExeModel===========" + gridCmdTemplates.getModel());
            if (gridCmdTemplates.getModel() == 0) {
                //登录后执行的命令
                String cmd = gridCmdTemplates.getExeCmd();
                logger.info("========ExeFun1====>>>=======" + cmd);
                CMDUtilShell cmdUtilShell = new CMDUtilShell();
                result = cmdUtilShell.executeCommands(cmd, item.getHostIp(), port, item.getUserName(), item.getUserPass(), newpasswd, 3000);
            } else if (gridCmdTemplates.getModel() == 1) {
                String shell = gridCmdTemplates.getExeShell();
                logger.info("========ExeFun2====>>>=======" + shell);
                ExpectShellUtil util = new ExpectShellUtil();
                result = util.executeShell(shell, item.getHostIp(), port, item.getUserName(), item.getUserPass(), newpasswd);
            }
            if (result.getCode() == 101) {
                map.put("pass", oldpass);
                map.put("code", 101);
                map.put("buffer", result.getMessages());
                map.put("msg", result.getMessages());
                log(item, map, newpasswd);
                return map;
            } else if (result.getCode() == 102) {
                map.put("pass", oldpass);
                map.put("code", 101);
                map.put("buffer", result.getMessages());
                map.put("msg", result.getMessages());
                log(item, map, newpasswd);
                return map;
            } else if (result.getCode() == 103) {
                map.put("pass", oldpass);
                map.put("code", 101);
                map.put("buffer", result.getMessages());
                map.put("msg", result.getMessages());
                log(item, map, newpasswd);
                return map;
            }
        }else
        {//自动模式只能通过定时器修改
            map.put("pass", oldpass);
            map.put("code", 1);
            map.put("buffer", "本设备采用自动模式,会自动修改");
            map.put("msg", "本设备采用自动模式,会自动修改");
            log(item, map, newpasswd);
            return map;
        }
        map.put("pass", newpasswd);
        map.put("code", 1);
        map.put("buffer", result.getMessages());
        map.put("msg", "提交成功");
        log(item, map, newpasswd);
        return map;
    }

    private void log(GridAccount item, HashMap map, String newpasswd) {
        GridLogs logs = new GridLogs();
        logs.setHostIp(item.getHostIp());
        logs.setHostName(item.getHostName());
        logs.setOldName(item.getUserName());
        logs.setOldPass(item.getUserPass());
        logs.setName(item.getUserName());
        logs.setPass(newpasswd);
        logs.setStatus("0");
        logs.setCreateBy(SecurityUtils.getUsername());
        logs.setRemark(map.toString());
        gridLogsService.insertGridLogs(logs);
    }


    @Log(title = "帐号管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:account:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<GridAccount> util = new ExcelUtil<GridAccount>(GridAccount.class);
        List<GridAccount> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = gridAccountService.importGridAccount(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<GridAccount> util = new ExcelUtil<GridAccount>(GridAccount.class);
        util.importTemplateExcel(response, "帐号数据");
    }


    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:account:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody GridAccount gridAccount) {
        gridAccount.setUpdateBy(getUsername());
        return toAjax(gridAccountService.updateGridPolicyStatus(gridAccount));
    }
}
